import config from '@/config'
import { Server } from '@/server'
import { globalLogger } from '@/log'
import { parseDebugConfig } from '@/utils/debug'
import { getErrorMessage } from '@/utils/error'
import { readConfigFileWithServer } from '@/configFile'
import type { CommandModule } from '@/types/cli'
import type { ServerDebugConfig } from '@/server'

const command: CommandModule = {
  name: 'server',
  description: 'start server',
  options: [
    {
      flags: '--debug',
      description: 'debug mode',
      ignore: !config.isDev
    },
    {
      flags: '--notUpdateHashMap',
      ignore: !config.isDev
    }
  ],
  action(_args, opts) {
    const debugConfig = parseDebugConfig<ServerDebugConfig>({
      debug: !!_args[0].debug && config.isDev,
      notUpdateHashMap: _args[0].notUpdateHashMap
    })

    try {
      const config = readConfigFileWithServer(opts.config)
      new Server(config, debugConfig)
    } catch (error) {
      globalLogger.server.error(getErrorMessage(error))
    }
  }
}

export default command
